今天我們要把 DAY 11 寫好的後端 GET API (/api/holdings) 透過 React Query 串接到前端,把朋友存在資料庫裡的寶可夢全都撈出來!
React Query 之所以能讓網頁感覺「秒開」,是因為它背後使用了 Stale-while-revalidate (過期但仍先顯示) 的快取策略:
我們只需要簡單定義一個 Fetcher 函式,然後丟給 useQuery:
import { useQuery } from '@tanstack/react-query';
import api from '../api/client';
// 1. 定義 Fetcher 函式 (透過 axios 發送請求)
const fetchHoldings = async () => {
const { data } = await api.get('/holdings');
return data; // 會自動帶著我們昨天設定的攔截器 Header!
};
// 2. 在元件中使用
const HoldingsPage = () => {
// isLoading 會自動幫我們判斷現在是不是還在等資料!
const { data: holdings, isLoading, error } = useQuery({
queryKey: ['holdings'],
queryFn: fetchHoldings
});
if (isLoading) return <div>載入圖鑑中...</div>;
if (error) return <div>發生錯誤囉</div>;
return (
<div>
{/* 把資料 map 出來 */}
{holdings?.map((pokemon) => (
<div key={pokemon.holding_id}>{pokemon.name_zh}</div>
))}
</div>
);
};

庫存管理網頁畫面,顯示出上面
map出來的寶可夢列表。
資料成功流進前端了!但現在只有純文字實在太無聊。明天,我們要出動 Material UI 的卡片 (Card) 系統,幫這些寶可夢設計漂亮的響應式展示介面!